package com.stadium.web.controller;

import com.fastsite.common.api.ApiResult;
import com.fastsite.common.api.ApiSecured;
import com.fastsite.common.enums.StatusEnum;
import com.stadium.web.domain.User;
import com.stadium.web.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 用户对象 user
 *
 * @author ruoyi
 * @date 2020-03-14
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/web/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 列表页面
     */
    @ApiOperation("用户列表信息")
    @ApiImplicitParams({
    @ApiImplicitParam(name="page",value="当前页数",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="size",value="每页的数量",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="id",value="主键",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="name",value="昵称",required=false,paramType="form",dataType="String"),
    @ApiImplicitParam(name="phone",value="手机号",required=false,paramType="form",dataType="String"),
    @ApiImplicitParam(name="sex",value="性别",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="age",value="年龄",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="balance",value="余额",required=false,paramType="form",dataType="Double"),
//    @ApiImplicitParam(name="createTime",value="创建时间",required=false,paramType="form",dataType="Date"),
    })
    @GetMapping("/list")
    public ApiResult index(@ApiIgnore User user){

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();
        matcher.withMatcher("name",match-> match.contains());
        // 获取用户列表
        Example<User> example = Example.of(user, matcher);

        Page<User> list = userService.getPageList(example);

        HashMap<String,Object> result = new HashMap<>();
        result.put("list", list.getContent());
        result.put("page", list);
        // 封装数据
        return ApiResult.ok(result,"获取用户列表信息");
    }

    /**
     * 跳转到编辑页面
     */
    @ApiOperation("单个用户信息")
    @GetMapping("/getOneUser")
    public ApiResult getOneUser(@RequestParam("id") Long id){
        User user=  userService.getById(id);
        return ApiResult.ok(user,"获取单个用户");
    }

    /**
     * 保存添加/修改的数据
     * @param userFrom 实体对象
     */
    @ApiSecured
    @ApiOperation(value = "保存/修改单个用户", authorizations = @Authorization(value = "token"), produces =  MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//    @ApiImplicitParam(name="id",value="主键",required=false,paramType="body",dataType="Long"),
//    @ApiImplicitParam(name="name",value="昵称",required=false,paramType="body",dataType="String"),
//    @ApiImplicitParam(name="phone",value="手机号",required=false,paramType="body",dataType="String"),
//    @ApiImplicitParam(name="sex",value="性别",required=false,paramType="body",dataType="Long"),
//    @ApiImplicitParam(name="age",value="年龄",required=false,paramType="body",dataType="Long"),
//    @ApiImplicitParam(name="balance",value="余额",required=false,paramType="body",dataType="Double"),
//    @ApiImplicitParam(name="createTime",value="创建时间",required=false,paramType="body",dataType="Date"),
//    })
    @PostMapping({"/save","/update"})
    public ApiResult save( @RequestBody User userFrom){
        User user = null;
        if(!StringUtils.isEmpty(userFrom.getId())){
            //修改
            user = userService.getById(userFrom.getId());

            user.setId(userFrom.getId());
                user.setName(userFrom.getName());
                user.setPhone(userFrom.getPhone());
                user.setSex(userFrom.getSex());
                user.setAge(userFrom.getAge());
                user.setBalance(userFrom.getBalance());
            }else{
            //新增
            user = new User();
            BeanUtils.copyProperties(userFrom,user);
            user.setCreateTime(new Date());
        }
        // 保存数据
        userService.save(user);
        return ApiResult.ok("保存成功");
    }


    /**
     * 设置一条或者多条数据的状态
     */

    @ApiOperation(value = "修改用户状态",hidden=true)
    @ApiImplicitParams({
            @ApiImplicitParam(name="param",value="状态（1:正常，2:冻结,3:删除）",required=true,paramType="path",dataType="String"),
            @ApiImplicitParam(name="ids",value="修改[id]",required=true,paramType="form",dataType="List")}
    )
    @RequestMapping(value = "/status/{param}",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ApiResult status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids){
        // 更新状态
        StatusEnum statusEnum = StatusEnum.getByCode(Byte.parseByte(param));
        if (userService.updateStatus(statusEnum, ids)) {
            return ApiResult.ok(statusEnum.getMessage() + "成功");
        } else {
            return ApiResult.err(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}

